<template>
	<div class="host">
		<HeaderLayout></HeaderLayout>
		<div class="box">
			<div class="content">
				<div class="chartRef" style="position: relative">
					<div style="position: absolute; top: 0; right: 0; z-index: 99999">
						<el-select
							v-model="yearOptionsModel"
							placeholder="Select"
							style="width: 130px"
							@change="handleYearOptionsModel(0)">
							<el-option
								v-for="item in yearOptions"
								:key="item.label"
								:label="item.label"
								:value="item.value" />
						</el-select>
					</div>
					<div :ref="sethostLineChartRef" style="flex: 1"></div>
					<!-- <div :ref="sethostLineChartRef"></div>
					<div :ref="sethostLineChartRef"></div> -->
				</div>
				<div class="chartRef" style="position: relative">
					<div style="position: absolute; top: 0; right: 0; z-index: 99999">
						<el-select
							v-model="yearOptionsModel"
							placeholder="Select"
							style="width: 130px"
							@change="handleYearOptionsModel(1)">
							<el-option
								v-for="item in yearOptions"
								:key="item.label"
								:label="item.label"
								:value="item.value" />
						</el-select>
					</div>
					<div :ref="sethostLineChartRef" style="flex: 1"></div>
					<!-- <div :ref="sethostLineChartRef"></div>
					<div :ref="sethostLineChartRef"></div>
					<div :ref="sethostLineChartRef"></div> -->
				</div>
				<div class="chartRef">
					<div style="flex: 1" class="fle relative">
						<div :ref="sethostLineChartRef" class="w-full h-full"></div>
						<div style="position: absolute; top: 0; right: 0; z-index: 99999">
							<el-select
								v-model="yearOptionsModel"
								placeholder="Select"
								style="width: 130px"
								@change="handleYearOptionsModel(2)">
								<el-option
									v-for="item in yearOptions"
									:key="item.label"
									:label="item.label"
									:value="item.value" />
							</el-select>
						</div>
					</div>
					<div style="flex: 1" class="fle relative">
						<div :ref="sethostLineChartRef" class="w-full h-full"></div>
						<div style="position: absolute; top: 0; right: 0; z-index: 99999">
							<el-select
								v-model="yearOptionsModel"
								placeholder="Select"
								style="width: 130px"
								@change="handleYearOptionsModel(3)">
								<el-option
									v-for="item in yearOptions"
									:key="item.label"
									:label="item.label"
									:value="item.value" />
							</el-select>
						</div>
					</div>
				</div>
			</div>
			<div class="panel"></div>
		</div>
	</div>
</template>

<script setup>
import labTable from '@/mixins/table.json'
import HeaderLayout from '@/layout/HeaderLayout.vue'
import { getEngieDate, engieDate, GearboxData, HostboxData, color } from '@/mixins/globalParam.js'
import {
	ENGINE_LEFT,
	ENGINE_RIGHT,
	ENGINE_LEFT_PW,
	ENGINE_RIGHT_PW,
	ENGINE_LEFT_ZC,
	ENGINE_RIGHT_ZC,
	ZC_LEN,
	PW_LEN,
	ENGINE_LEFT_SUPERCHARGER,
	ENGINE_RIGHT_SUPERCHARGER,
	ENGINE_LEFT_INFO,
	ENGINE_RIGHT_INFO,
	SUPERCHARGER_LEN
} from '@/utils/const.js'
import { http } from '@/api/http.js'
import moment from 'moment'
import momentRange from 'moment-range'
let yearOptions = ref([
	{
		value: '2024',
		label: '2024年'
	},
	{
		value: '2025',
		label: '2025年'
	},
	{
		value: '2026',
		label: '2026年'
	}
])

let yearOptionsModel = ref('2024')
let engine = inject('engine')
let Echarts = inject('$echarts')
let defaultParmas = {}
let rightFields = [
	...ENGINE_RIGHT_PW,
	...ENGINE_RIGHT_ZC,
	...ENGINE_RIGHT_SUPERCHARGER,
	...ENGINE_RIGHT_INFO
]
let leftFields = [
	...ENGINE_LEFT_PW,
	...ENGINE_LEFT_ZC,
	...ENGINE_LEFT_SUPERCHARGER,
	...ENGINE_LEFT_INFO
]
let fields = ref(engine.value == ENGINE_LEFT ? leftFields : rightFields)
let fieldData = ref(engine.value == ENGINE_LEFT ? labTable.left_main : labTable.right_main)
let parmas = reactive({
	measurementName: engine.value,
	start: moment.utc('2024-05-01').startOf('day').format(),
	stop: moment.utc('2024-06-01').startOf('day').format(),
	fields: [...fields.value].join('_'),
	unit: 'mo'
})
let hostLineChartRef = ref([])
let sethostLineChartRef = (el) => {
	hostLineChartRef.value.push(el)
}
let ChnegPAIEcharts = reactive([])
let chartDataList = ref([])
let getCurrentEngineFiled = computed(() => {
	return (lV, rV) => {
		return engine.value == ENGINE_LEFT ? lV : rV
	}
})
let getCurrentEngineFiledbyIndex = computed(() => {
	return (lVAry, rVAry, index) => {
		return engine.value == ENGINE_LEFT ? lVAry[index] : rVAry[index]
	}
})

let modelList = reactive([
	{
		title: '排气温度',
		fields: fields.value.slice(0, PW_LEN),
		dataTime: {
			mo: moment().year(),
			d: moment().month(),
			z: 1,
			h: moment().date()
		},
		max: 800,
		interval: 50
	},
	{
		title: '轴承温度',
		fields: fields.value.slice(PW_LEN, PW_LEN + ZC_LEN + 1),
		dataTime: {
			mo: moment().year(),
			d: moment().month(),
			z: 1,
			h: moment().date()
		},
		max: 150,
		interval: 30
	},
	{
		title: '增压器',
		fields: fields.value.slice(PW_LEN + ZC_LEN + 1, PW_LEN + ZC_LEN + SUPERCHARGER_LEN + 1),
		dataTime: {
			mo: moment().year(),
			d: moment().month(),
			z: 1,
			h: moment().date()
		},
		max: 1000,
		interval: 50
	},
	{
		title: '主机信息',
		fields: fields.value.slice(PW_LEN + ZC_LEN + SUPERCHARGER_LEN + 1),
		dataTime: {
			mo: moment().year(),
			d: moment().month(),
			z: 1,
			h: moment().date()
		},
		max: 1000,
		interval: 50
	}
])
let setMonth = (year, month) => {
	// 创建一个表示该月第一天的moment对象
	let firstDayOfMonth = moment()
		.year(year)
		.month(month - 1)
		.date(1)

	// 由于moment.js核心库没有直接的daysInMonth方法，我们可以通过克隆这个日期对象并加一个月，然后减去一天来得到该月的最后一天
	let lastDayOfMonth = firstDayOfMonth.clone().add(1, 'months').subtract(1, 'days')

	// 获取最后一天的日期，即该月的天数
	let daysInMonth = lastDayOfMonth.date()
	return daysInMonth
}
const dateTime = {
	mo: [
		'Jan', // January
		'Feb', // February
		'Mar', // March
		'Apr', // April
		'May', // May
		'Jun', // June
		'Jul', // July
		'Aug', // August
		'Sep', // September
		'Oct', // October
		'Nov', // November
		'Dec' // December
	],
	d: new Array(setMonth(new Date().getFullYear(), new Date().getMonth() + 1))
		.fill()
		.map((item, i) => i + 1 + 'D'),
	h: new Array(24).fill().map((item, i) => i + 1 + 'H'),
	m: new Array(60).fill().map((item, i) => i + 1 + 'M'),
	s: []
}

const setSeriesTheme = (len) => {
	return [
		{
			type: 'line',
			smooth: true,
			symbol: 'none',
			label: {
				show: true,
				position: 'top',
				color: '#fff',
				fontSize: 12
			},
			seriesLayoutBy: 'row',
			areaStyle: {
				opacity: 0.8,
				color: {
					colorStops: [
						{
							offset: 0,
							color: 'rgba(73, 146, 255, 0.5)'
						},
						{
							offset: 1,
							color: 'rgba(73, 146, 255, 0)'
						}
					],
					x: 0,
					y: 0,
					x2: 0,
					y2: 1,
					type: 'linear',
					global: false
				}
			},
			lineStyle: {
				color: 'rgba(73, 146, 255, 1)'
			},
			itemStyle: {
				emphasis: {
					color: 'rgba(73, 146, 255, 1)'
				},
				color: 'rgba(73, 146, 255, 1)'
			}
		},
		{
			type: 'line',
			smooth: true,
			symbol: 'none',
			lineStyle: {
				color: '#25e0e5'
			},
			itemStyle: {
				color: '#25e0e5',
				emphasis: {
					color: '#25e0e5'
				}
			},
			seriesLayoutBy: 'row',
			areaStyle: {
				opacity: 0.8,
				color: {
					colorStops: [
						{
							offset: 0,
							color: 'rgba(37, 244, 299, 0.5)'
						},
						{
							offset: 1,
							color: 'rgba(37, 244, 299, 0)'
						}
					],
					x: 0,
					y: 0,
					x2: 0,
					y2: 1,
					type: 'linear',
					global: false
				}
			},
			emphasis: {
				focus: 'series'
			}
		},
		{
			type: 'line',
			smooth: true,
			symbol: 'none',
			label: {
				show: true,
				position: 'top',
				color: '#fff',
				fontSize: 12
			},
			seriesLayoutBy: 'row',
			areaStyle: {
				opacity: 0.8,
				color: {
					colorStops: [
						{
							offset: 0,
							color: 'rgba(70, 246, 205, 0.5)'
						},
						{
							offset: 1,
							color: 'rgba(70, 246, 205, 0)'
						}
					],
					x: 0,
					y: 0,
					x2: 0,
					y2: 1,
					type: 'linear',
					global: false
				}
			},
			emphasis: {
				focus: 'series'
			},
			lineStyle: {
				color: 'rgba(70, 146, 205, 1)'
			},
			itemStyle: {
				color: 'rgba(70, 146, 205, 1)',
				emphasis: {
					color: 'rgba(70, 146, 205, 1)'
				}
			}
		},
		{
			type: 'line',
			smooth: true,
			symbol: 'none',
			label: {
				show: true,
				position: 'top',
				color: '#fff',
				fontSize: 12
			},
			seriesLayoutBy: 'row',
			areaStyle: {
				opacity: 0.8,
				color: {
					colorStops: [
						{
							offset: 0,
							color: 'rgba(73, 146, 255, 0.5)'
						},
						{
							offset: 1,
							color: 'rgba(73, 146, 255, 0)'
						}
					],
					x: 0,
					y: 0,
					x2: 0,
					y2: 1,
					type: 'linear',
					global: false
				}
			},
			lineStyle: {
				color: 'rgba(73, 146, 255, 1)'
			},
			itemStyle: {
				color: 'rgba(73, 146, 255, 1)',
				emphasis: {
					color: '#25e0e5'
				}
			}
		},
		{
			type: 'line',
			smooth: true,
			symbol: 'none',
			label: {
				show: true,
				position: 'top',
				color: '#fff',
				fontSize: 12
			},
			seriesLayoutBy: 'row',
			areaStyle: {
				opacity: 0.8,
				color: {
					colorStops: [
						{
							offset: 0,
							color: 'rgba(73, 60, 255, 0.5)'
						},
						{
							offset: 1,
							color: 'rgba(73, 60, 255, 0)'
						}
					],
					x: 0,
					y: 0,
					x2: 0,
					y2: 1,
					type: 'linear',
					global: false
				}
			},
			lineStyle: {
				color: 'rgba(73, 60, 255, 1)'
			},
			itemStyle: {
				color: 'rgba(73, 60, 255, 1)',
				emphasis: {
					color: 'rgba(73, 60, 255, 1)'
				}
			}
		},
		{
			type: 'line',
			smooth: true,
			symbol: 'none',
			label: {
				show: true,
				position: 'top',
				color: '#fff',
				fontSize: 12
			},
			seriesLayoutBy: 'row',
			areaStyle: {
				opacity: 0.8,
				color: {
					colorStops: [
						{
							offset: 0,
							color: 'rgba(73, 6, 25, 0.5)'
						},
						{
							offset: 1,
							color: 'rgba(73, 6, 25, 0.5)'
						}
					],
					x: 0,
					y: 0,
					x2: 0,
					y2: 1,
					type: 'linear',
					global: false
				}
			},
			lineStyle: {
				color: 'rgba(73, 6, 25, 1)'
			},
			itemStyle: {
				color: 'rgba(73, 6, 25,1)',
				emphasis: {
					color: 'rgba(73, 6, 25,1)'
				}
			}
		},
		{
			// name: '7#缸排气温度',
			type: 'line',
			smooth: true,
			symbol: 'none',
			label: {
				show: true,
				position: 'top',
				color: '#fff',
				fontSize: 12
			},
			seriesLayoutBy: 'row',
			areaStyle: {
				opacity: 0.8,
				color: {
					colorStops: [
						{
							offset: 0,
							color: 'rgba(3, 6, 25, 0.5)'
						},
						{
							offset: 1,
							color: 'rgba(3, 6, 25, 0.5)'
						}
					],
					x: 0,
					y: 0,
					x2: 0,
					y2: 1,
					type: 'linear',
					global: false
				}
			},
			lineStyle: {
				color: 'rgba(3, 6, 25, 1)'
			},
			itemStyle: {
				color: 'rgba(3, 6, 25,1)'
			}
		}
	].slice(0, len)
}

const setOption = ({ max, interval, data, series }) => {
	return {
		dataset: {
			source: [...data]
		},
		tooltip: {
			trigger: 'axis',
			textStyle: {
				color: '#ccc'
			},
			axisPointer: {
				type: 'cross'
			}
		},
		dataZoom: [
			{
				type: 'slider', // 滑动条型数据区域选择组件
				start: 0, // 左边在 10% 的位置
				end: 60,
				max: 90,
				min: 10 // 右边在 60% 的位置
				// xAxisIndex: 0, // 仅当存在多个 xAxis 时，指定该 dataZoom 控件控制哪个 xAxis
				// 其他的配置项如：showDataShadow、backgroundColor、handleStyle 等
			},
			{
				type: 'inside', // 内置型数据区域选择组件，只在区域内部有效
				start: 10,
				end: 60,
				maxValueSpan: 5,
				zoomLock: true
			}
		],

		xAxis: [
			{
				type: 'category',
				gridIndex: 0,
				boundaryGap: false,
				axisTick: {
					show: true
				},
				axisLine: {
					symbol: false
				},
				axisLabel: {
					show: true,
					fontSize: 12,
					interval: 0
					// rotate: 40
				},
				triggerEvent: true
			}
		],
		grid: {
			show: true
		},
		yAxis: [
			{
				gridIndex: 0,
				min: 0,
				max,
				interval
			}
		],
		series
	}
}
const setTheme = function (model, i, { legend,grid = {} }) {
	return {
		legend: {
			data: legend,
			icon: 'rect',
			type: 'scroll',
			top: '6%',
			align: 'right',
			padding: [13, 13, 13, 13],
			itemGap: 13,
			itemWidth: 29,
			itemHeight: 19,
			itemStyle: {
				borderType: 'dashed'
			}
		},
		title: {
			text: model.title,
			left: 'center'
		},
		grid: {
			top: '20%',
			bottom: 50,
			containLabel: true,
      ...grid
		},
		graphic: [
			{
				type: 'rect',
				left: '15%',
				top: '14%',
				shape: { width: 50, height: 25 },
				style: {
					fill: '#409EFF',
					text: '年',
					textFill: '#fff',
					fontSize: 14,
					textAlign: 'center',
					textVerticalAlign: 'middle'
				},
				onclick: async function (item) {
					console.log('年按钮被点击了！')
					await onClick('mo', i)
				}
			},
			{
				type: 'rect',
				left: '30%',
				top: '14%',
				shape: { width: 50, height: 25 },
				style: {
					fill: '#409EFF',
					text: '月',
					textFill: '#fff',
					fontSize: 14,
					textAlign: 'center',
					textVerticalAlign: 'middle'
				},
				onclick: async function (item) {
					console.log('月按钮被点击了！')
					await onClick('d', i)
				}
			},
			{
				type: 'rect',
				left: '45%',
				top: '14%',
				shape: { width: 50, height: 25 },
				style: {
					fill: '#409EFF',
					text: '周',
					textFill: '#fff',
					fontSize: 14,
					textAlign: 'center',
					textVerticalAlign: 'middle'
				},
				onclick: function () {
					console.log('周按钮被点击了！')
				}
			},
			{
				type: 'rect',
				left: '60%',
				top: '14%',
				shape: { width: 50, height: 25 },
				style: {
					fill: '#409EFF',
					text: '日',
					textFill: '#fff',
					fontSize: 14,
					textAlign: 'center',
					textVerticalAlign: 'middle'
				},
				onclick: async function () {
					console.log('日按钮被点击了！')
					await onClick('h', i)
				}
			}
		]
	}
}
let getListData = async () => {
	let res = await http('GET')('/getAllData', parmas)
	chartDataList.value = res.list
}

let formart = (unit, dateTime) => {
	let { mo, d, z, h } = dateTime
	let date = {}
	switch (unit) {
		case 'mo':
			date['start'] = moment.utc({ year: +mo }).format()
			date['stop'] = moment.utc({ year: +mo + 1 }).format()
			break
		case 'd':
			date['start'] = moment.utc({ year: mo, month: d }).format()
			date['stop'] = moment.utc({ year: mo, month: d }).add(1, 'month').format()
			break
		case 'z':
			date['start'] = moment.utc({ year: mo, month: d }).format()
			date['stop'] = moment.utc({ year: mo, month: d }).format()
			break
		case 'h':
			date['start'] = moment.utc({ year: mo, month: d, date: h }).format()
			date['stop'] = moment.utc({ year: mo, month: d, date: h }).add(1, 'day').format()
			break
		default:
			break
	}

	return date
}

const handleYearOptionsModel = async (index) => {
	let model = modelList[index]
	let unit = 'mo'
	modelList[index].dataTime[unit] = yearOptionsModel.value
	let tmpBody = {
		...parmas,
		unit,
		...formart(unit, model.dataTime),
		fields: model.fields.join('_')
	}
	parmas = tmpBody
	await getListData()
	setCharts(ChnegPAIEcharts[index], model, index, unit)
}

const initData = async () => {
	await getListData()
}
const getFiledsData = (filed) => {
	return chartDataList.value.filter((item) => item._field == filed)
}

const getFiledsValue = (fields, index, data) => {
	let fieldsData = {}
	fields.forEach((value) => {
		if (!(value in fieldsData)) {
			fieldsData[value] =
				data.filter((item) => item._field == value && item._time == index)[0]?._value || '0'
		}
	})
	return fieldsData
}
const setSource = (mode, time = 'mo') => {
	let data = []
		.concat(
			mode.fields.map((item) => {
				return getFiledsData(item)
			})
		)
		.flat()
	let source = dateTime[time].map((item, index) => {
		return {
			name: item,
			...getFiledsValue(mode.fields, index, data)
		}
	})
	let filrateData = []
	mode.fields.forEach((item) => {
		let arr = []
		arr[0] = fieldData.value[item].name.slice(3)
		let dataArr = source.filter((jitem) => Object.keys(jitem).includes(item))
		let temp = dataArr.map((kitem) => (kitem = parseFloat(kitem[item]))).flat()
		arr.push(...temp)
		filrateData.push(arr)
	})
	console.log('=============source', [['type', ...dateTime[time]], ...filrateData])
	return [['product', ...dateTime[time]], ...filrateData]
}

const getextByFileds = (fileds) => {
	let filedsArr = fileds.map((item) => (item = fieldData.value[item]?.name.slice(3)))
	return filedsArr
}

const getUnitByValue = (value) => {
	if (dateTime['mo'].includes(value)) {
		return 'd'
	} else if (dateTime['d'].includes(value)) {
		return 'h'
	} else if (dateTime['h'].includes(value)) {
		return 'h'
	} else if (dateTime['z'].includes(value)) {
		return 'z'
	} else {
		return 'mo'
	}
}
const handleClickxAxis = async (e, index) => {
	console.log('=====================handleClickxAxis', e, index)
	let { tickIndex, value, componentType } = e
	if (componentType == 'xAxis') {
		let unit = getUnitByValue(value)
		let model = modelList[index]
		modelList[index].dataTime[unit] = unit == 'd' ? tickIndex : tickIndex + 1
		let tmpBody = {
			...parmas,
			unit,
			...formart(unit, model.dataTime),
			fields: model.fields.join('_')
		}
		parmas = tmpBody
		await getListData()
		setCharts(ChnegPAIEcharts[index], model, index, unit)
	}
}
const setCharts = (el, model, index, unit = 'mo') => {
	console.log('===============setCharts')
	let option = setOption({
		max: model.max,
		interval: model.interval,
		data: setSource(model, unit),
		series: setSeriesTheme(model.fields.length)
	})

	el.setOption(setTheme(model, index, { legend: getextByFileds(model.fields) }))
	el.setOption(option)
	console.log("===============option",{
		...setTheme(model, index, { legend: getextByFileds(model.fields) }),
		...option
	})
}
const onClick = async (unit, index) => {
	let model = modelList[index]
	let tmpBody = {
		...parmas,
		unit,
		...formart(unit, model.dataTime),
		fields: model.fields.join('_')
	}
	parmas = tmpBody
	await getListData()
	setCharts(ChnegPAIEcharts[index], model, index, unit)
}

let initChart = () => {
	try {
		hostLineChartRef.value.forEach((item, i) => {
			let model = modelList[i]
			ChnegPAIEcharts[i] = Echarts.init(item)
			setCharts(ChnegPAIEcharts[i], model, i)
			ChnegPAIEcharts[i].on('click', (e) => handleClickxAxis(e, i))
		})
	} catch (error) {
		console.log('================errpr', error)
	}
}

const clearEchartsHandle = (index) => {
	if (isNaN(index + 1)) {
		ChnegPAIEcharts.forEach((item) => {
			item?.off('click', () => {
				console.log('=============解绑click')
			})
		})
		return
	}
	console.log('============213')
	ChnegPAIEcharts[index]?.off('click', () => {
		console.log('=============解绑click')
	})
}

onMounted(async () => {
	await initData()
	initChart()
})
onUnmounted(() => {
	// clearEchartsHandle()
	//   clearInterval(timer.value);
})
</script>
<style scoped lang="scss">
.host {
	height: 100%;
	display: flex;
	flex-direction: column;
	.box {
		height: 90%;
		width: 100%;
		display: flex;
		box-sizing: border-box;
		padding: 15px;
		// background: #1a1918;
	}
	.content {
		width: 100%;
		display: flex;
		.chartRef {
			display: flex;
			flex-direction: column;
			flex: 1;
			height: 100%;
		}
		.detail {
			width: 50%;
			height: 100%;
			display: flex;
			flex-direction: column;
			.cargin {
				display: flex;
				justify-content: end;
				span {
					cursor: pointer;
					margin-left: 15px;
				}
			}
			.content {
				flex: 1;
				width: 100%;
			}
		}
	}
	.panel {
		width: 0%;
	}
}

// .btn-group{
//     display: flex;
//     margin: 0 auto;
// // }
// .host {
// 	height: 100%;
// 	display: flex;
// 	flex-wrap: wrap;
// 	background: rgb(45, 73, 97);
// 	& > div {
// 		height: 50%;
// 		width: 450px;
// 	}
// }
// :deep(.el-button--large.is-round) {
// 	padding: 12px 32px;
// }
</style>
